/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2022-12-29 10:15:38
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-10-12 09:00:20
 * @FilePath: \cxl-admin\src\components\accountEditDialog\index.ts
 */
import { addUser, AddUserParas, editUser, MenuItem, UserParas } from '@/apis/system/account'
import { selectCompany } from '@/apis/company/audit'
import { getAllMenuTree, getMenuTreeById } from '@/apis/system/menu'
import { handleTree, regMobile } from '@/utils'
import { ElMessage } from 'element-plus'
import { nextTick, reactive, ref } from 'vue'
import { userStore } from '@/store/user.store'
import { bubbleSort } from '@/store/router.store'

export class EditDialogData {
    //定义开户的基本信息字段
    information: any = reactive({
        visible: false, //显示隐藏
        title: '编辑', //标题
        width: '752px', //弹窗宽度
        type: 'edit', //弹窗类型
        isEditAdmin: false, //是否是编辑管理员用户
        companyName: '', //公司名称
        companyId: '', //公司id
        id: '', //公司id
        phone: '', //电话
        password: '', //登录密码
        status: true, //状态
        defaultPassword: '', //默认密码
        companyAdminFlag: 1
    })

    //定义基本信息表单的验证
    rules: any = {
        companyName: { required: true, message: '请选择公司', trigger: 'change' },
        phone: { required: true, validator: this.phoneValidatePass, trigger: 'blur' },
        password: { required: true, message: '请输入登录密码', trigger: 'blur' },
        name: { required: true, message: '请输入姓名', trigger: 'blur' }
    }

    //定义公司选择器
    companyOptions: any[] = reactive([])
    //定义菜单权限列表
    listTree: any[] = reactive([])
    //定义是否勾选全部
    checkedAllMenu = false
    //定义当前弹窗是 create | edit
    type = 'create'
    //定义默认的密码
    defaultPassword: string | undefined = '••••••'
    /**
     * 定义tree子菜单字段及显示字段
     */
    defaultProps = {
        children: 'children',
        label: 'name',
        id: 'id'
    }
    /**
     * 定义权限选择的内容
     */
    checkedId: any[] = reactive([])
    /**
     * 定义是否开始搜索
     */
    loading = ref(false)
    //是否是超级管理员
    isSuperAdmin = ref(false)
    //本地用户仓库
    _userStore: any
    //展示表格数据内容
    tableData: any[] = reactive([])
    //分页
    pagination = reactive({
        pageNo: 1,
        pageSize: 20,
        total: 0
    })
    constructor() {
        this._userStore = userStore()
        this.isSuperAdmin.value = this._userStore.isSuperAdmin
        console.log('this.isSuperAdmin.value', this.isSuperAdmin.value)
    }

    /**
     * 监听选择的当前分页
     * @param index
     */
    onPaginationChange = (index: number) => {
        console.log(index)
        this.pagination.pageNo = index
        this.getCompanyList()
    }
    /**
     * 监听分页大小的改变
     * @param index
     */
    onPaginationSize = (index: number) => {
        console.log(index)
        this.pagination.pageSize = index
        this.getCompanyList()
    }
    /**
     * 监听检索选择的企业id
     * @param res
     */
    onSelectCompanyId = (id: string) => {
        this.information.id = id
    }

    /**
     * 监听密码修改
     */
    onPasswordChange = (res: string) => {
        console.log(res)
        this.information.password = res.trim()
    }
    onPasswordFocus = () => {
        this.information.password = ''
    }

    /**
     * 验证输入的是否是正确的手机号
     * @param rule
     * @param value
     * @param callback
     */
    phoneValidatePass(rule: any, value: any, callback: any) {
        if (value === '') {
            callback(new Error('请输入手机号码'))
        } else {
            regMobile(value) ? callback() : callback(new Error('手机号有误，请重新输入'))
        }
    }

    /**
     * 获取公司
     * @param name
     * @param callback
     */
    getCompanyList(name = '', callback = () => {}) {
        selectCompany({ current: 1, size: 10, companyParam: name }).then(res => {
            if (res.data.value === 200) {
                this.companyOptions.length = 0
                res.data.data.records.map((item: any) => {
                    this.companyOptions.push({ value: item.companyId, label: `${item.companyName}` })
                })
                // this.tableData.length = 0
                // this.tableData.push(...res.data.data.records)
                // this.pagination.total = res.data.data.total
                callback()
            }
        })
    }
    originTree: any[] = []
    /**
     * 查询菜单树
     */
    getMenuTree(superAdmin: boolean, id: string, treeRef: any, callback: () => void) {
        if (superAdmin) {
            console.log('是否是编辑管理员信息', this.information.isEditAdmin)
            /**
             * 超级管理员
             * 区分当前弹窗是 编辑管理员信息 | 编辑员工信息
             */

            getAllMenuTree().then((res: any) => {
                this.listTree.length = 0
                this.listTree.push(...bubbleSort(handleTree(res, 'id', 'parentId')))
                this.originTree.length = 0
                this.originTree.push(...res)
                callback()
                console.log('超级管理员listTree', this.listTree)
            })
        } else {
            //企业管理员 获取该企业所拥有的权限
            getMenuTreeById(id).then((res: any) => {
                if (res.data.value === 200) {
                    this.listTree.length = 0
                    this.listTree.push(...bubbleSort(handleTree(res.data.data, 'id', 'parentId')))
                    this.originTree.length = 0
                    this.originTree.push(...res.data.data)
                    treeRef.value?.setData(this.listTree)
                    callback()
                    console.log('企业管理员listTree', this.listTree)
                }
            })
        }
    }

    appendParent(list: any[]) {
        //定义map
        const map = new Map()
        //存放结果数组
        const result: any[] = []
        //定义是否添加了父级
        let isAdd = false
        //将选择的勾选的元素转换成map结构
        list.forEach((item: any) => {
            map.set(item.id, item)
        })
        //通过遍历选择的元素列表，判断元素的父级是否存在列表中，不存在则把其父元素添加到map数组中，设置isAdd=true
        list.forEach(item => {
            if (!map.has(item.parentId)) {
                this.originTree.forEach(child => {
                    if (item.parentId === child.id) {
                        map.set(child.id, child)
                        isAdd = true
                    }
                })
            }
        })
        //遍历map 生成新的勾选元素数组
        map.forEach((value: any) => {
            result.push(value)
        })
        //根据isAdd 判断是否需要进行新的遍历
        if (isAdd) {
            isAdd = false
            result.push(...this.appendParent(result))
        }
        //返回过滤重复的元素
        return new Set([...result])
    }

    /**
     * 提交表单数据
     * @param list
     * @param callback
     */
    onSubmit(selectList: any[], callback = () => {}) {
        const menuList: MenuItem[] = []
        const params: AddUserParas = {
            phone: this.information.phone,
            status: this.information.status ? 1 : 0,
            menuResourceDTOList: menuList,
            name: this.information.name,
            companyAdminFlag: this.information.isEditAdmin ? 1 : 0
        }

        //遍历map数据，根据MenuItem接口返回对应的数据
        const map = this.appendParent(selectList) || []
        map.forEach((value: any) => {
            menuList.push({
                id: value.id,
                parentId: value.parentId,
                type: value.type
            })
        })

        console.log('information', this.information)
        if (this.type == 'edit') {
            //修改保存
            //判断密码是否修改过
            if (this.information.password !== this.defaultPassword) {
                params.password = this.information.password
            }
            //由于params属于 AddUserParas ，且 AddUserParas 中 没有 id 属性， 所以需要进行类型断言
            const query: UserParas = params
            console.log('information', this.information)
            query.id = this.information.id

            console.log('query', query)
            editUser(query).then(res => {
                if (res?.data.value === 200) {
                    ElMessage.success('修改成功')
                    callback()
                } else {
                    ElMessage.error(res.data.desc)
                }
            })
        } else {
            //新增保存
            params.password = this.information.password
            params.companyId = this.information.companyId || this.information.id
            console.log('params', params)
            addUser(params).then(res => {
                if (res?.data.value === 200) {
                    ElMessage.success('新增成功')
                    callback()
                } else {
                    ElMessage.error(res.data.desc)
                }
            })
        }
    }

    /**
     * 重置数据
     */
    resetData = () => {
        this.checkedId.length = 0
        this.information.companyName = ''
        this.information.id = ''
        this.information.phone = ''
        this.information.password = ''
        this.information.name = ''
        this.information.companyId = ''

        this.information.visible = false
    }

    /**
     * 监听用户输入的公司名，搜索
     * @param query
     */
    remoteMethod = (query: string) => {
        if (query) {
            this.loading.value = true
            this.getCompanyList(query, () => {
                this.loading.value = false
            })
        }
    }

    /**
     * 监听选择的公司
     * @param res
     */
    onSelectCompany = (res: any) => {
        console.log(res)
        this.information.companyId = res
    }

    /**
     * 拉取用户所拥有的权限
     */
    // ownTree: any[] = reactive([])

    deletePermission = (list: any[], noPermissionList: any[]) => {
        const resultList = JSON.parse(JSON.stringify(list))
        const parent: any[] = []
        const arr: any[] = []
        resultList.forEach((item: any) => {
            noPermissionList.forEach((child: any, index: number) => {
                if (item.id === child.parentId) {
                    if (item.parentId !== '') {
                        parent.push(item)
                    }
                    resultList.splice(index, 1)
                    console.log(item.name, item.id, child.parentId)
                }
            })
        })
        if (parent.length) {
            arr.length = 0
            arr.push(...this.deletePermission(resultList, parent))
            console.log(this.deletePermission(resultList, parent))
        }
        return parent.length ? arr : resultList
    }

    getUserOwnMenuTree = (treeRef: any) => {
        getMenuTreeById(this.information.id).then((res: any) => {
            const result: any[] = [...res.data.data]
            console.log('用户权限', result)
            console.log('默认权限', this.originTree)

            const resultPermissionArray: any[] = []
            //从基础的权限中 过滤parentId == '' 和 存在 children 的元素 最后得到用户的权限
            const resultList = [...this.originTree]
            resultList.forEach((item: any) => {
                result.forEach((child: any) => {
                    if (item.id === child.id && !item.children) {
                        resultPermissionArray.push(item)
                    }
                })
            })
            console.log('用户的权限', resultList, this.information.id, this.information.companyId)

            this.checkedId.length = 0
            if (Number(this.information.id) === 1) {
                resultList.forEach((item: any) => {
                    this.checkedId.push(item.id)
                })
            } else {
                resultPermissionArray.forEach(item => {
                    this.checkedId.push(item.id)
                })
            }

            console.log('checkedId', this.checkedId)
            //猜测首次渲染，显示没有执行
            const timer = setTimeout(() => {
                treeRef.value?.setCheckedKeys(this.checkedId)
                clearTimeout(timer)
            }, 100)

            this.information.visible = true
        })
    }
}
